import axios from 'axios';

// 统一的 API 配置
const API_BASE_URL = 'https://zhi1develop.zicp.fun/v1';

const getBotId = () => localStorage.getItem('bot_id') || 'app-7sIPOisuxuQCwMapf3GBojjQ';

const service = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000,
  withCredentials: false,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Authorization': `Bearer ${getBotId()}`
  }
});

service.interceptors.request.use(
  config => {
    // 每次请求时重新获取 bot_id，确保使用最新的值
    config.headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Authorization': `Bearer ${getBotId()}`
    };
    return config;
  },
  error => {
    console.error('Request error:', error);
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  response => {
    return response.data;
  },
  error => {
    if (error.response) {
      // 处理 401 错误
      if (error.response.status === 401) {
        console.error('Authentication failed:', error.response.data);
      }
      console.error('Response error:', error.response.data);
    } else {
      console.error('Network error:', error.message);
    }
    return Promise.reject(error);
  }
);

export default service;
export { API_BASE_URL, getBotId }; 